package homework.handler;

import com.sun.net.httpserver.HttpExchange;
import homework.RequestMethod;
import homework.Resource;
import homework.manager.Beans;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public abstract class AbstractRequestHandler<T> implements RequestHandler<T> {
    private final Set<String> requestMethod;

    public AbstractRequestHandler() {
        requestMethod = new HashSet<>(Arrays.asList(this.getClass().getAnnotation(RequestMethod.class).value()));
        for (Field field : this.getClass().getDeclaredFields()) {
            if (field.isAnnotationPresent(Resource.class)) {
                Object manager = Beans.getBean(field.getType());
                try {
                    if(field.isAccessible()) {
                        field.set(this, manager);
                    } else {
                        field.setAccessible(true);
                        field.set(this, manager);
                        field.setAccessible(false);
                    }
                } catch (IllegalAccessException e) {
                    System.out.println("注入Manager出错：" + field.getName());
                }
            }
        }
    }

    @Override
    public Set<String> requestMethod() {
        return requestMethod;
    }

    protected void response(HttpExchange exchange, String response) throws IOException {
        sendResponse(exchange, response, 200);
    }

    protected void error(HttpExchange exchange, String error) throws IOException {
        sendResponse(exchange, error, 400);
    }

    private void sendResponse(HttpExchange exchange, String response, int statusCode) throws IOException {
        byte[] bytes = response.getBytes();
        exchange.sendResponseHeaders(statusCode, bytes.length);
        OutputStream os = exchange.getResponseBody();
        os.write(bytes);
        os.close();
    }
}
